/* eslint-disable react/jsx-indent */
/* eslint-disable no-nested-ternary */
import React, { Component, Suspense } from "react";
import PageHeaderWrapper from "@/components/PageHeaderWrapper";
import qs from "qs";
import { connect } from "dva";
import PageLoading from "@/components/PageLoading";
import { FormattedMessage } from "umi-plugin-react/locale";
import {
	Card,
	Row,
	Col,
	Form,
	Input,
	Button,
	message,
	Icon,
	Checkbox,
	Table,
	Tag,
	Select,
	Modal,
	Radio,
	Spin,
	Upload,
	Tabs,
	Tooltip,
} from "antd";
import Custom from "./custom.js";
import CustomNew from "./customNew";
import download from "@/utils/download";
import { routerRedux } from "dva/router";
import axios from "axios";
import BackRouter from "@/pages/CapacityStudy/KnowledgeSmartMaintenance/backRouter";
import deleteimg from "@/assets/buttonimg/delete.png";
const { TabPane } = Tabs;
const FormItem = Form.Item;
const Search = Input.Search;
const InputGroup = Input.Group;
import styles from "./index.less";
const { Option } = Select;
const { TextArea } = Input;
const RadioGroup = Radio.Group;
import pen from "../../../assets/icons/bi.png";
import ljx from "../../../assets/icons/垃圾箱.png";

class EnumerableNew extends Component {
	constructor(props) {
		super(props);
		// let items = JSON.parse(props.location.query.id)
		const { id, urlPrefix } = this.props.match.params;
		this.state = {
			disabled: true,
			name: id
				? props.location.query.name
				: decodeURIComponent(window.location.href.split("?")[1].split("&")[1]),
			// name:items.name,
			okid: id
				? props.location.query.id
				: decodeURIComponent(window.location.href.split("?")[1].split("&")[0]),
			// okid:items.id,
			okname: id
				? props.location.query.name
				: decodeURIComponent(window.location.href.split("?")[1].split("&")[1]),
			// okname:items.name,
			mockValue: "",
			pageA: 1,
			limit: 10,
			itemNames: "",
			totab: "",
			dataSource2: [],
			listday: [],
			itemId: "",
			formatA: "",
			formatB: "",
			formatC: "",
			listday: [],
			showModel1: false,
			showModel2: false,
			tcxModel: false,
			login: true,
			fileList: [],
			uploading: false,
			uploadId: {
				dictId: id
					? id
					: decodeURIComponent(
						window.location.href.split("?")[1].split("&")[0]
					),
			},
			urlPrefix,
			// uploadId: { dictId: items.id }
		};
	}

	componentDidMount() {
		//
		// 新增部分
		const { id } = this.props.match.params;
		if (id) {
			this.setState({ okid: id }, () => {
				this.fetchb();
			});
		} else {
			this.setState(
				{
					okid: decodeURIComponent(
						window.location.href.split("?")[1].split("&")[0]
					),
					okname: decodeURIComponent(
						window.location.href.split("?")[1].split("&")[1]
					),
					uploadId: {
						dictId: decodeURIComponent(
							window.location.href.split("?")[1].split("&")[0]
						),
					},
				},
				() => {
					this.fetchb();
				}
			);
		}
	}

	fetchb = () => {
		this.setState({
			login: true,
			dataSource2: [],
		});

		const { dispatch, currentUser } = this.props;
		const { okid, pageA, limit, itemNames } = this.state;
		const { urlPrefix } = this.props.match.params;

		this.reqRef = requestAnimationFrame(() => {
			dispatch({
				type: "customDictionary/enumList",
				payload: {
					modelId: okid,
					current: pageA,
					size: limit,
					search: itemNames,
					urlPrefix,
				},
				callback: (res) => {
					let a = res.records;
					a.map((item, index) => {
						item["key"] = index;
					});
					this.setState({
						dataSource2: a,
						listday: a,
						totab: res.total,
						login: false,
					});
				},
			});
		});
	};

	checkField(rule, value, callback) {
		const reg = /^[\u4e00-\u9fa5a-zA-Z0-9]+$/g;
		if (rule.field === "namecid") {
			if (value) {
				if (reg.test(value)) {
					if (value.length > 20 || value.length < 0) {
						callback("支持20位以内大小写字母、数字和中文");
					} else {
						callback();
					}
				} else {
					callback("支持20位以内大小写字母、数字和中文");
				}
			} else {
				callback("支持20位以内大小写字母、数字和中文");
			}
		}
	}

	// 词典名称修改
	textInput = () => {
		const { urlPrefix } = this.state;
		const { tabKey } = this.props.location.query;
		const { getFieldDecorator } = this.props.form;
		return (
			<div className={styles.flexcen}>
				<Form layout='inline' onSubmit={this.handleSubmit}>
					<FormItem label='实体名称'>
						{getFieldDecorator("namecid", {
							initialValue: this.state.name,
							rules: [
								{
									required: true,
									message: "实体名称必填",
								},
								{ validator: this.checkField },
							],
						})(
							<Input
								disabled={this.state.disabled}
								onPressEnter={this.saveChanges}
								onChange={this.namegai}
							/>
						)}
					</FormItem>
					{this.state.disabled === true ? (
						urlPrefix ? null : (
							<span>
								<Icon
									onClick={this.modifyClick}
									className={styles.fleximg}
									type='edit'
								/>
							</span>
						)
					) : (
						<span>
							<Icon
								onClick={this.bcClick}
								className={styles.fleximg}
								type='check'
							/>
						</span>
					)}
				</Form>
			</div>
		);
	};

	returnButton = () => {
		const { location } = this.props;
		const listPage = location.query.page;
		return (
			<BackRouter
				style={{ float: "right" }}
				pathname='/knowledgeDesign/customDictionary'
				listPage={listPage}></BackRouter>
		);
	};

	namegai = (e) => {
		this.setState({ mockValue: e.target.value });
	};

	// 字典名称显示或隐藏
	modifyClick = () => {
		this.setState({
			disabled: false,
		});
	};

	bcClick = () => {
		const reg = /^[\u4e00-\u9fa5a-zA-Z0-9]+$/g;

		if (this.state.mockValue === "") {
			if (
				reg.test(this.state.okname) &&
				this.state.okname.length < 21 &&
				this.state.okname > 0
			) {
				this.setState({
					disabled: true,
				});
				const { dispatch } = this.props;
				this.reqRef = requestAnimationFrame(() => {
					dispatch({
						type: "customDictionary/fetche",
						payload: { id: this.state.okid, name: this.state.okname },
						callback: (res) => {
							message["info"](`${res.message}`);
						},
					});
				});
			}
		} else {
			if (
				reg.test(this.state.mockValue) &&
				this.state.mockValue.length < 21 &&
				this.state.mockValue.length > 0
			) {
				this.setState({
					disabled: true,
				});
				const { dispatch } = this.props;
				this.reqRef = requestAnimationFrame(() => {
					dispatch({
						type: "customDictionary/fetche",
						payload: { id: this.state.okid, name: this.state.mockValue },
						callback: (res) => {
							message["info"](`${res.message}`);
						},
					});
				});
			}
		}
	};

	onChangeB = (val) => {
		// 页数选择

		this.setState({ pageA: val }, () => {
			this.fetchb();
		});
	};

	// 每页显示多少条数据
	onShowSizeChangeB = (current, pageSize) => {
		this.setState({ pageA: current, limit: pageSize }, () => {
			this.fetchb();
		});
	};

	// 子页面修改内容
	enumeration = () => {
		this.props.form.setFields({ coreword: "" });
		this.props.form.setFields({ synonym: "" });
		this.setState({
			formatA: "",
			formatB: "",
			showModel2: true,
		});
	};

	// 子页面
	coreWord = () => {
		let userInfo = this.props.form.getFieldsValue(); // 获取数据
		this.props.form.validateFields((err, values) => {
			// 校验方法
			let userInfo = this.props.form.getFieldsValue(); // 获取数据
			let reg = /^[a-zA-Z0-9\u4e00-\u9fa5\,，]+$/;

			if (!err) {
				if (userInfo.coreword.length > 30) {
					return message.info("核心词不能大于30字符");
				}
				// if (userInfo.synonym !="" && !reg.test(userInfo.synonym)) {
				//   return message.info('同义词请输入汉字、数字、字母等字符')
				// }
				if (userInfo.coreword !== "") {
					const { dispatch, currentUser } = this.props;
					let url = "customDictionary/fetchf";
					let obj = {
						modelId: this.state.okid,
						word: userInfo.coreword,
						synWords: userInfo.synonym,
					};
					if (this.state.itemId) {
						obj.id = this.state.itemId;
						url = "customDictionary/fetchWordEdit";
					}
					this.reqRef = requestAnimationFrame(() => {
						dispatch({ type: url, payload: obj, callback: (res) => {
							if (typeof res.code !== 'undefined' && res.code !== 0) {
								// message["error"](`${res.message}`);
							} else {
								message.success(`${res.msg}`);
								this.setState({ showModel2: false, pageA: 1, itemId: "", }, () => {
									this.fetchb(this.state.okid, this.state.pageA, this.state.pageSizeA, this.state.ziyevalue);
								});
							}
						}});
					});
				} else {
					message["warning"]("请添加核心词");
				}
			}
		});
	};

	handleEdit = (item) => {
		this.props.form.setFields({ coreword: "" });
		this.props.form.setFields({ synonym: "" });
		this.setState({
			formatA: item.word,
			formatB: item.synWords.join(","),
			itemId: item.id, // _id
			showModel2: true,
		});
	};

	fromDeletes = (item) => {
		const text = item.isUse
			? "该自定义实体正在被使用中，删除后将影响机器人的正常问答，是否确定删除"
			: "确定删除吗？";
		Modal["confirm"]({
			title: "删除任务",
			content: text,
			okText: "删除",
			cancelText: "取消",
			onOk: () => {
				const { dispatch } = this.props;
				this.reqRef = requestAnimationFrame(() => {
					dispatch({
						type: "customDictionary/fetchg",
						payload: { id: item.id },
						callback: (res) => {
							this.fetchb();
							message.info(res.message);
						},
					});
				});
			},
			onCancel() { },
		});
	};

	answerDetail = () => {
		if (this.state.totab === 0) {
			message.error("空列表无法导出！");
		} else {
			const { dispatch, currentUser } = this.props;
			const { itemNames } = this.state;
			let object = {};

			object.dictId = this.state.uploadId.dictId;
			object.dictItemNames = this.state.itemNames;
			dispatch({
				type: "customDictionary/exporta",
				payload: object,
				callback: (res) => {
					let filename = decodeURIComponent(
						res.requestRes.headers.get("Content-Disposition").split("=")[1]
					);
					download.byBlob(res.fileBlob, filename);
				},
			});
		}
	};

	toLeadt = () => {
		this.setState({ tcxModel: true });
	};

	handleUpFile = (info) => {
		let fileList = [...info.fileList];
		fileList = fileList.slice(-1);
		fileList = fileList.map((file) => {
			if (file.response) {
				file.url = file.response.url;
			}
			return file;
		});
		if (fileList[0].size / 1024 / 1024 > 2) {
			message.error("上传文件超出2M");
			this.setState({ fileList: [] });
		} else {
			this.setState({ fileList });
		}
	};

	uploadFile = (data) => {
		const { dispatch } = this.props;
		// const token = JSON.parse(window.localStorage.getItem("currentUser")) == undefined ? '' : JSON.parse(window.localStorage.getItem("currentUser")).token;
		dispatch({
			type: "customDictionary/importa",
			payload: data,
			callback: (res) => {
				this.setState(
					{
						uploading: false,
					},
					() => {
						if (res.data.code) {
							this.fetchb();
							return message.error(res.data.msg);
						} else {
							this.fetchb();
							this.setState(
								{
									tcxModel: false,
									visible: false,
									fileList: [],
								},
								() => {
									if (res.data.msg) {
										message.success(res.data.msg);
									} else {
										message.success("导入成功");
									}
								}
							);
						}
					}
				);
			},
		});
		// axios.post('/cloud/basic/dict/import', data, {
		//   method: 'post',
		//   processData: false,
		//   headers: { "Content-Type": "application/json", "token": token }
		// }).then((res) => {
		//   this.setState({
		//     uploading: false
		//   }, () => {
		//     if (res.data.code) {
		//       this.fetchb()
		//       return message.error(res.data.msg)
		//     } else {
		//       this.fetchb()
		//       this.setState({
		//         tcxModel: false,
		//         visible: false,
		//         fileList: []
		//       }, () => {
		//         if (res.data.msg) {
		//           message.success(res.data.msg);
		//         } else {
		//           message.success('导入成功');

		//         }
		//       });

		//     }
		//   })
		// }).catch((error) => {
		//   message.error('导入失败请稍等再试')
		// });
	};

	businessWayA = () => {
		const { fileList, uploadId } = this.state;

		const formData = new FormData();
		fileList.forEach((file) => {
			formData.append("file", file.originFileObj);
			formData.append("dictId", uploadId.dictId);
		});
		this.setState({
			uploading: true,
		});
		this.uploadFile(formData);
	};

	handleCancel = () => {
		this.setState({ tcxModel: false, uploading: false, fileList: [] });
	};

	// 下载模版
	dictTemp = () => {
		const { dispatch, currentUser } = this.props;
		dispatch({
			type: "customDictionary/templateA",
			payload: {},
			callback: (res) => {
				let filename = decodeURIComponent(
					res.requestRes.headers.get("Content-Disposition").split("=")[1]
				);
				download.byBlob(res.fileBlob, filename);
			},
		});
	};

	Tooltipzdy = () => {
		return (
			<div>
				{`添加/编译实体`}
				<span style={{ marginLeft: 12, paddingTop: 3 }}>
					<Tooltip
						placement='top'
						title='核心词：必填。不可带有标点符号和各种括号。词典名称是该词典下所有核心词的统称。同义词：核心词的同义词。选填。同义词之间以中英文逗号隔开。'
						arrowPointAtCenter>
						<Icon style={{ fontSize: 14 }} type='info-circle' />
					</Tooltip>
				</span>
			</div>
		);
	};

	render() {
		const { urlPrefix } = this.props.match.params;
		const { tabKey } = this.props.location.query;
		let columns1 = [
			{
				title: (
					<FormattedMessage
						id='app.customDictionary.core-word'
						defaultMessage='coreWord'
					/>
				),
				width: "calc(30vw)",
				dataIndex: "word",
			},
			{
				title: (
					<FormattedMessage
						id='app.customDictionary.core-agreed'
						defaultMessage='agreed'
					/>
				),
				width: "calc(40vw)",
				dataIndex: "synWords",
				render: (synWords) => (
					<span>
						{synWords.map((tag, index) => {
							let color = index % 2 == 1 ? "#5092e1" : "#87d3ac";
							return (
								<span title={tag} key={tag}>
									<Tag
										style={{
											marginBottom: 2,
											maxWidth: "calc(30vw)",
											wordWrap: " break-word",
											wordBreak: " break-all",
											overflow: "hidden",
											textOverflow: "ellipsis",
										}}
										color={color}
										key={tag}>
										{tag}
									</Tag>
								</span>
							);
						})}
					</span>
				),
			},
			{
				title: (
					<FormattedMessage
						id='app.customDictionary.operation'
						defaultMessage='operation'
					/>
				),
				dataIndex: "sex",
				render: (text, item) => {
					return (
						<div className={styles.pb}>
							<div
								className={styles.buttongl}
								onClick={(text) => {
									this.handleEdit(item);
								}}>
								<img style={{ marginRight: 5 }} src={pen} />
								<span style={{ marginBottom: 1 }}>
									<FormattedMessage
										id='app.customDictionary.edit'
										defaultMessage='Edit'
									/>
								</span>
							</div>
							<div
								style={{ marginLeft: 10, background: "#e8313b" }}
								className={styles.buttongl}
								onClick={(text) => {
									this.fromDeletes(item);
								}}>
								<img src={deleteimg} style={{ marginRight: 5 }} />
								<span style={{ marginBottom: 1 }}>
									{" "}
									<FormattedMessage
										id='app.customDictionary.out'
										defaultMessage='out'
									/>
								</span>
							</div>
						</div>
					);
				},
			},
		];
		if (urlPrefix) {
			columns1 = [
				{
					title: (
						<FormattedMessage
							id='app.customDictionary.core-word'
							defaultMessage='coreWord'
						/>
					),
					width: "calc(30vw)",
					dataIndex: "word",
				},
				{
					title: (
						<FormattedMessage
							id='app.customDictionary.core-agreed'
							defaultMessage='agreed'
						/>
					),
					width: "calc(40vw)",
					dataIndex: "synWords",
					render: (synWords) => (
						<span>
							{synWords.map((tag, index) => {
								let color = index % 2 == 1 ? "#5092e1" : "#87d3ac";
								return (
									<span title={tag} key={tag}>
										<Tag
											style={{
												marginBottom: 2,
												maxWidth: "calc(30vw)",
												wordWrap: " break-word",
												wordBreak: " break-all",
												overflow: "hidden",
												textOverflow: "ellipsis",
											}}
											color={color}
											key={tag}>
											{tag}
										</Tag>
									</span>
								);
							})}
						</span>
					),
				},
			];
		}

		const { getFieldDecorator } = this.props.form;
		const FormItemLayont = {
			labelCol: {
				// 文字
				xs: 24,
				sm: 4,
			},
			wrapperCol: {
				// 输入框
				xs: 24,
				sm: 20,
			},
		};
		const { uploading, fileList } = this.state;
		const props1 = {
			onRemove: (file) => {
				this.setState((state) => {
					const index = state.fileList.indexOf(file);
					const newFileList = state.fileList.slice();
					newFileList.splice(index, 1);
					return {
						fileList: newFileList,
					};
				});
			},
			beforeUpload: (file) => {
				this.setState((state) => ({
					fileList: [...state.fileList, file],
				}));
				return false;
			},
			accept: ".xlsx",
			fileList,
			onChange: this.handleUpFile,
		};

		return (
			<Suspense fallback={<PageLoading />}>
				<PageHeaderWrapper>
					<div className={styles.backgroundp}>
						<Row className={styles.colorBackground}>
							<Col
								style={{ padding: 10, color: "#4B5475", fontWeight: 600 }}
								xs={24}
								className={styles.colorA}>
								<span className={styles.title}>
									<span>实体详情</span>
									{this.returnButton()}
								</span>
							</Col>
						</Row>
						{this.textInput()}
						<Card bordered={false}>
							<div className={styles.fromColumn}>
								<span className={styles.right} style={{ display: 'flex', alignItems: 'center', gap: 16 }}>
									<Input
										placeholder='请输入搜索核心词'
										onChange={e => this.setState({ itemNames: e.target.value })}
										style={{ width: 323 }}
									/>
									<Button type="primary" onClick={() => this.setState({ pageA: 1 }, () => this.fetchb())}>查询</Button>
								</span>
								{urlPrefix ? null : (
									<span className='buttonYs'>
										<Button onClick={this.enumeration} type="primary">新增</Button>
									</span>
								)}
							</div>
							<Spin spinning={this.state.login}>
								<Table // 可枚举类型
									className='zdyTable'
									style={{ padding: "20px 0px 0px 0px" }}
									columns={columns1}
									dataSource={this.state.dataSource2} // 数据
									onChange={this.handleChange}
									pagination={{
										// 分页
										total: this.state.totab,
										pageSize: this.state.limit, // 显示几条一页
										current: this.state.pageA, // 当前页
										showSizeChanger: true, // 是否显示可以设置几条一页的选项
										showQuickJumper: true,
										onChange: this.onChangeB,
										onShowSizeChange: this.onShowSizeChangeB,
									}}
								/>
							</Spin>
						</Card>
						<Modal
							className='modelZdy'
							title={this.Tooltipzdy()}
							visible={this.state.showModel2}
							okText={<FormattedMessage id='app.customDictionary.save' />}
							cancelText={<FormattedMessage id='app.customDictionary.cancel' />}
							onCancel={() => {
								this.setState({
									showModel2: false,
									itemId: "",
								});
							}}
							onOk={this.coreWord} // 确定方法开出去
						>
							<Form layout='horizontal'>
								<FormItem
									label={
										<FormattedMessage id='app.customDictionary.core-word' />
									}
									onSubmit={this.coreWord}
									{...FormItemLayont}>
									{getFieldDecorator("coreword", {
										initialValue: `${this.state.formatA}`,
										rules: [
											{ required: true, message: "核心词不能为空" },
											(rule, value = "", callback) => {
												try {
													if (value.length > 30) {
														callback("核心词不可超过30个字符");
													}
													callback();
												} catch (err) {
													callback(err);
												}
											},
										],
									})(<Input />)}
								</FormItem>
								<FormItem
									label={
										<FormattedMessage id='app.customDictionary.core-agreed' />
									}
									{...FormItemLayont}>
									{getFieldDecorator("synonym", {
										initialValue: `${this.state.formatB}`,
									})(
										<TextArea
											placeholder='请输入同义词名称，可填写多个，请以中英文逗号分隔'
											autoSize={{
												minRows: 4,
												maxRows: 6,
											}}
										/>
									)}
								</FormItem>
							</Form>
						</Modal>
						<Modal
							className='modelZdy'
							width={550}
							title='上传实体'
							visible={this.state.tcxModel}
							footer={[
								<Button key='back' onClick={this.handleCancel}>
									取消
								</Button>,
								<Button
									key='submit'
									type='primary'
									loading={uploading}
									disabled={fileList.length === 0}
									onClick={this.businessWayA}>
									{uploading ? "导入中" : "开始导入"}
								</Button>,
							]}
							onCancel={() => {
								this.setState({
									tcxModel: false,
									uploading: false,
									fileList: [],
								});
							}}>
							<Form layout='horizontal'>
								<FormItem label='选择文件' {...FormItemLayont}>
									<Upload {...props1} fileList={this.state.fileList}>
										<Button>
											<Icon type='upload' /> 选择文件
										</Button>
									</Upload>
								</FormItem>
								<FormItem label='上传规则' {...FormItemLayont}>
									<div className={styles.frame}>
										<div>
											<span>• 请按照模板中的示例格式进行编辑上传：</span>{" "}
											<span onClick={this.dictTemp} className={styles.template}>
												下载xlsx模版
											</span>
										</div>
										<div>
											<span>• 上传文件格式需要为“.xlsx”类型的Excel文件</span>
										</div>
										<div>
											<span>• 导入的实体数据将覆盖现有数据，请谨慎操作</span>
										</div>
									</div>
								</FormItem>
							</Form>
						</Modal>
					</div>
				</PageHeaderWrapper>
			</Suspense>
		);
	}
}

export default connect(({ user }) => ({
	// 全局数据
	currentUser: user.currentUser,
}))(Form.create()(EnumerableNew));
